﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;

namespace CLUBsInterpreter.Visual
{
	class UserInterface
	{
		public CanvasForm Canvas;

		public UserInterface(Size s)
		{
			Canvas = new CanvasForm();
			Canvas.ClientSize = s;
			// TODO: Add form close handler
			Thread t = new Thread(new ThreadStart(delegate() { CreateForm(Canvas); }));
			t.Start();
			while (!Canvas.InvokeRequired) { }
		}

		private void CreateForm(CanvasForm c)
		{
			Application.Run(c);
		}

		public void AddPaintable(IPaintable elem)
		{
			Canvas.Paint += elem.Paint;
			Refresh();
		}

		public void AddClickable(IClickable elem)
		{
			Canvas.MouseClick += elem.OnClick;
		}

		public void Refresh()
		{
			if (Canvas.InvokeRequired)
			{
				Action callback = Refresh;
				Canvas.Invoke(callback);
			}
			else
			{
				Canvas.Refresh();
			}
		}

		public void Show()
		{
			// InvokeRequired compares the thread ID of the
			// calling thread to the thread ID of the creating thread.
			// If these threads are different, it returns true.
			if (Canvas.InvokeRequired)
			{
				Action callback = Show;
				Canvas.Invoke(callback);
			}
			else
			{
				Canvas.Show();
			}
		}

		public void Close()
		{
			if (Canvas.InvokeRequired)
			{
				Action callback = Close;
				Canvas.Invoke(callback);
			}
			else
			{
				Canvas.Dispose();
				Canvas = null;
				Application.Exit();
			}
		}

	}
}
